<?php

require_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action {
    
    public function newAction() {
        $this->view->messages = $this->_helper->FlashMessenger->getMessages();
    }
    
    public function viewAction() {
        $user = Model_User::getUser(array('id' => $this->getRequest()->getParam('id', null)));
        $this->view->messages = $this->_helper->FlashMessenger->getMessages();
        $this->view->first_name = $user->first_name;
        $this->view->last_name = $user->last_name;
        $this->view->email = $user->email;
    }
    
    public function createAction() {
        if ($this->getRequest()->isPost()) {
            //$data = $this->getRequest()->getPost();
            $user = new Model_User($this->getRequest()->getPost());
            if ($user->isValid()) {
                $user->save();
                $this->_helper->FlashMessenger('Registración exitosa!');
                $this->_helper->redirector->gotoSimple('view', 'user', null, array('id' => $user->id));
            }
            else {
                $this->_generateErrorMessage($user->getMessages());
            }
        }
        $this->_helper->redirector->gotoSimple('new');
    }
    
    private function _generateErrorMessage($messages) {
        if (is_array($messages)) {
            foreach ($messages as $fields) {
                foreach ($fields as $error) {
                    $this->_helper->FlashMessenger->addMessage($error);
                }
            }
        }
        else {
            $this->_helper->FlashMessenger->addMessage($messages);
        }
    }
    
}